layui.use(['form','layer','layedit','laytpl','laypage','element','jquery'],function(){
    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : parent.layer,
        layedit = layui.layedit,
        layPage = layui.laypage,
        laytpl = layui.laytpl,
        element = layui.element,
        $ = layui.jquery;

    //验证是否已登录
    if(isNotLogIn()){
        return;
    }
    var managerId = getCookie("managerId");
    var msgTpl = "{" +
        "{# layui.each(d.data, function(index, item){ }}<tr itemid=\"{{item.MSG_ID}}\"><td><input type=\"checkbox\" name=\"checked\" lay-skin=\"primary\" lay-filter=\"choose\"></td><td>{{item.REAL_NAME}}</td><td>{{item.MSG_CONTENT}}</td><td>{{item.MSG_TYPE}}</td><td><form class='layui-form' action=''><div class='layui-input-inline'><input {{# if ( '1'==item.READ_TAG){ }} checked= 'true'{{# } }} name='open' lay-skin='switch' lay-filter='isValid' lay-text='是|否' type='checkbox' disabled></div></form> </td> <td>{{item.CREATE_TIME}}</td> <td><button class='layui-btn layui-btn-normal layui-btn-sm edit-btn'><i class='layui-icon'>&#xe611;</i></button> </td><td><button class='layui-btn layui-btn-sm layui-btn-danger delete-btn'><i class='layui-icon'>&#xe640;</i></button></td></tr>{{# }); }}";
    var type = "";
    var count = 0;
    var readTag = "0";
    var managerLevel = getCookie("managerLevel");
    var msgTypeSelectHtml = "<select name=\"msgColl\" lay-filter=\"selectMsg\">\n" +
        "\t\t\t\t\t<option value='0'>全部消息</option><option value='1'>公告</option>\n" +
        "\t\t\t        <option value='2'>聊天消息</option>\n";
    if(managerLevel=="02"){
        msgTypeSelectHtml += "<option value='3'>举报消息</option>";
    }
    if(managerLevel=="99"){
        msgTypeSelectHtml += "<option value='3'>举报消息</option><option value='4'>局长信箱</option>";
    }
    //监听消息类型选择框
    $("#selectMsg").html(msgTypeSelectHtml+"</select>");
    form.render('select');
    form.on('select(selectMsg)',function (data) {
        var msgTypeCheck = data.value;
        if(msgTypeCheck != type){
            type = msgTypeCheck;
            getMsgInfo(type,readTag);
            removeAllSel();
        }
    });
    //监听已读未读消息切换
    element.tabChange('msg_search',"0"); //切换到相应lay-id类型
    //获取新闻信息,默认获取最新动态
    getMsgInfo(type,readTag);
    element.on('tab(msg_search)', function(data){
        var isRead = $(this).attr("lay-id");
        if(readTag==isRead){
            return;
        }
        readTag = isRead;
        //重新加载一个表格
        getMsgInfo(type,readTag);
        removeAllSel();
    });


    //获取消息列表
    function getMsgInfo(msgType,isRead,page,limit){
        if(isNotLogIn()){
            return;
        }
        msgType = isNull(msgType)?"":msgType;
        isRead = isNull(isRead)?"0":isRead;
        page = isNull(page)?0:page;
        limit = isNull(limit)?10:limit;
        var index = layer.load(3);
        //清空当前数据
        $(".msgHtml").html("");
        $.ajax({
            url:"/CivilAffairs/msg/getMsgInfo",
            type : "post",
            data : {"msgType":msgType,"isRead":isRead,"managerId":managerId,"page":page,"limit":limit},
            async : false,
            dataType : "json",
            success : function(result) {
                layer.close(index);
                if(checkResult(result)){
                    laytpl(msgTpl).render(result.data.data, function(html) {
                        $(".msgHtml").html(html);
                    });
                    //重新渲染
                    form.render('checkbox');
                    //需要重新加载分页
                    if(count!=result.data.count ||type != msgType){
                        count = result.data.count;
                        type = msgType;
                        //分页组件
                        layPage.render({
                            elem: 'news-page'
                            ,count: result.data.count //数据总数，从服务端得到
                            ,layout: ['count', 'prev', 'page', 'next', 'limit', 'skip']
                            ,jump: function(obj, first){
                                //首次不执行
                                if(!first){
                                    console.log("not first");
                                    getMsgInfo(msgType,isRead,page,limit)
                                }
                            }
                        });
                    }
                }else{
                    count = 0;
                    type = msgType;
                    //分页组件
                    layPage.render({
                        elem: 'news-page'
                        ,count: result.data.count //数据总数，从服务端得到
                        ,layout: ['count', 'prev', 'page', 'next', 'limit', 'skip']
                        ,jump: function(obj, first){
                            //首次不执行
                            if(!first){
                                console.log("not first");
                                getMsgInfo(msgType,isRead,page,limit)
                            }
                        }
                    });
                }
            },
            error : function(result) {
                layer.close(index);
                reqError(result,"管理员获取新闻异常");
            }
        });
    }

    //全选
    form.on('checkbox(selectAll)', function(data){
        var child = $(data.elem).parents('table').find('tbody input[name="checked"]:not([name="open"])');
        child.each(function(index, item){
            item.checked = data.elem.checked;
        });
        form.render('checkbox');
    });

    //通过判断文章是否全部选中来确定全选按钮是否选中
    form.on("checkbox(choose)",function(data){
        var child = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="open"])');
        var childChecked = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="open"]):checked')
        if(childChecked.length == child.length){
            var selectAll = $(data.elem).parents('table').find('thead input#selectAll').get(0);
            selectAll.checked = true;
        }else{
            var selectAll = $(data.elem).parents('table').find('thead input#selectAll').get(0);
            selectAll.checked = false;
        }
        form.render('checkbox');
    });

    //删除
    $("body").on("click",".delete-btn",function(){
        if(isNotLogIn()){
            return;
        }
        var manager = getCookie("managerId");
        var _this = $(this);
        layer.confirm('确定删除此信息？',{icon:3, title:'提示信息'},function(index){
            //_this.parents("tr").remove();
            var msgId = _this.parents("tr").attr("itemid");
            deleteMsg(msgId,manager);
            layer.close(index);
        });
        return false;
    });

    //批量删除
    $(".batchDel").click(function(){
        if(isNotLogIn()){
            return;
        }
        var manager = getCookie("managerId");
        var $checkbox = $('.msgHtml tr input[name="checked"]');
        var $checked = $('.msgHtml tr input[name="checked"]:checked');
        if($checkbox.is(":checked")){
            layer.confirm('确定删除选中的信息？',{icon:3, title:'提示信息'},function(index){
                //判断选中的消息是否有未读消息
                $checked.each(function(){
                    var input = $(this).parents("tr").find('input[name="open"]');
                    var isRead = $(input).checked;
                    //有未读消息则不允许删除
                    if(!isRead){
                        layer.close(index);
                        layer.msg("含有未读消息，不允许删除，请先阅读",{icon:2});
                        return false;
                    }
                });
                var index = layer.msg('删除中，请稍候',{icon: 16,time:false,shade:0.8});
                //删除数据
                $checked.each(function(){
                    var msgId = $(this).parents("tr").attr("itemid");
                    deleteMsg(msgId,manager,true);
                });
                getMsgInfo(type,readTag,0,10);
                layer.close(index);
                layer.msg("删除成功",{icon:6});
            })
        }else{
            layer.msg("请选择需要删除的信息");
        }
    });

    //删除信息
    function deleteMsg(msgId,managerId,isAllDel){
        if(isNull(msgId)){
            return;
        }
        $.ajax({
            url : "/CivilAffairs/msg/deleteMsg",
            type : "post",
            data : {"msgId":msgId,"managerId":managerId},
            async : false,
            dataType : "json",
            success : function(result) {
                if(checkResult(result) && !isAllDel){
                    getMsgInfo(type,readTag,0,10);
                }
            },
            error:function(result){
                reqError(result,"删除信息异常");
            }
        });
    }

    //阅读消息
    $("body").on("click",".edit-btn",function(){
        if(isNotLogIn()){
            return;
        }
        var manager = getCookie("managerId");
        var msgId = $(this).parents("tr").attr("itemid");
        $(window).one("resize",function(){
            //编辑文章
            var index = layui.layer.open({
                title : "阅读信息",
                type : 2,
                closeBtn: 0,
                content : "messageReply.html?msgId="+msgId,
                success : function(layero, index){
                    // setTimeout(function(){
                    //     layui.layer.tips('点击此处返回消息列表', '.layui-layer-setwin .layui-layer-close', {
                    //         tips: 3
                    //     });
                    // },500)
                }
            });
            layui.layer.full(index);
        }).resize();
        return false;
    });
});


